سفارش تبلیغ
صبا ویژن

web development

Enabling Xamarin Push Notifications for all platforms

    نظر

Xamarin is a programming language based on the C # programming language. With CAM-based programming in xamarin, you can get three different outputs at the same time, outputs for Android applications, IOS applications and Windows applications.

Enable Xamarin push notifications for all platforms

What are push notifications?

Push notifications are notifications that are sent to users by the server without the user request. Push notifications are called push notifications because notifications are sent to users by the server without the user request. Of course, this does not mean that the server can send any relevant or unrelated information to the user, but it does mean that the user first activates the service and makes the relevant settings and notifications from The server side is sent to it automatically before the user requests.
Users can change the settings for push notifications if needed, or even disable them if they wish.
One of the most important features and benefits of push notifications is that no special program is required to receive these notifications and notifications will be sent and received even when the phone screen is off.
Updates are done on smartphones with different Android and IOS operating systems . Developers of these operating systems also use different methods to send notifications. Developers of Android operating system use Google Cloud Messaging or Firebase Cloud Messaging service to send information to phones with Android operating system. The Apple Push Notification Services API is used to send information to iOS operating systems.

How are push notifications sent?

There are different technologies for sending pressure notifications that each site and company uses different technologies to send pressure notifications on their site.

These technologies include the following:


• Apple Push Notification Service (APNS)
• Google Cloud Messaging (GCM)
• Windows Push Notification Services (WNS)
Sending push notifications cannot be done directly. To send notifications, you must make sure that there is a support service, after the user confirms to send push notifications, automatically and before the user requests, the site notifications are sent to the user be.
Launched in 2001, the Mono developers developers organized the platform. Xamarin is an open source platform built on the .NET framework that provides opportunities for development in the Microsoft environment. Following the announcement of Xamarin as an open source platform, it became part of the Xamarin Visual Studio Integrated Development Environment (IDE).
Xamarin can also be used to send push notifications to extended applications. This is usually the same as sending notifications via Google Firebase
The Firebase Cloud Messaging Service (FCM) is available for sending message notifications and more.

How to enable XAMARIN push notifications:

Azure notification hub is commonly used to send notifications to an Android Xamarin app. These notifications are played on all Android devices using the Firebase Cloud Messaging feature.
Hub is used to transfer information to Xamarin. Forms applications. Transfer notifications to Xamarin.Forms applications used to target Android and iOS operating systems. To use the best and latest installation methods, it is best to use the ASP.NET Core Web API extension, which sends push notifications and notifications cross-platform.

In this tutorial you will learn the following note:


• Set up Push Notification and Azure Notification Hub services.
• How to setup google notification cloud messaging or Firebase Cloud Messaging (FCM)
• How to implement push notifications for
Android apps .
• How to implement push notifications for
iOS apps .
• How to send push notifications.
• How to receive and process push notifications.

Basic Requirements:


• Mac computer with Visual Studio installed.
• Install Xamarin and .NET with Visual Studio.
• Ability to run a Xamarin application on both Android and iOS platform.
• Physical device or emulator (capable of running API 26 and above using applications installed on the Google Play service.)

Implementation of Push Notification on Xamarin Android:



1- Go to https://console.firebase.google.com and signup and create a project for your app. (this will be useful for all platforms)
2- In the cloud messaging settings, download and add google-services.json to Xamarin.Android project root.
3- Right click on google-services.json in Visual studio and set the buildaction => googleJson
4- Install nuget package => xamarin.firebase.messaging for android 60.11
5- Install nuget package => xamarin.googleplayservices.base
6- remove all green-icon android support nuget pacakages (if exist)
7- update all other available nugets
8- Add this Code to your AndroidManifest.xml file inside the application tag.

<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>


9- In your MainActivity.cs File, you can add this:

public static string NotificationToken = "";

protected override void OnCreate(Bundle savedInstanceState)
{
try
{
//Register for Notification Channel
FirebaseApp app = FirebaseApp.InitializeApp(Android.App.Application.Context);
AdnroidNotification.CreateNotificationChannel();
//Notification Click Action
if (!string.IsNullOrEmpty(act.Intent.GetStringExtra("ClickAction")))
{
//WRITE YOUR CLICK ACTION HERE
using (service as IDisposable)
{
service.Open(act.Intent.GetStringExtra("ClickAction"));
}
}
}
catch
{

}

base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());

}



10- Create a class in you Xamarin.Android project and add this code:

public class AdnroidNotification
{
public static readonly int NOTIFICATION_ID = 1000;
public static readonly string CHANNEL_ID = "general_notification";
public static readonly string CHANNEL_NAME = "General Notification";
public static void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O) return;
var channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationImportance.Default) { Description = CHANNEL_NAME };
var notificationManager = (NotificationManager)Notification.Act.GetSystemService(Context.NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
}

[Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class FirebaseRegistrationService : FirebaseInstanceIdService
{
public override void OnTokenRefresh()
{
FirebaseMessaging.Instance.SubscribeToTopic("all");
Modules.Notification.CheckRegisteringDevice();
}
}

[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class FirebaseNotificationService : FirebaseMessagingService
{
public override void OnMessageReceived(RemoteMessage message)
{
try
{
string MessageTitle = "", MessageBody = "", MessageClickAction = "", MessageSound = "";
try
{
MessageTitle = message.Data["MessageTitle"];
MessageBody = message.Data["MessageBody"];
MessageSound = message.Data["MessageSound"];
MessageClickAction = message.Data["MessageClickAction"];
}
catch
{
}
if (string.IsNullOrWhiteSpace(MessageBody)) return;
ShowNotification(MessageTitle, MessageBody, MessageClickAction, MessageSound);
}
catch (Exception ex)
{
}
}

public void ShowNotification(string Title, string Body, string ClickAction, string Sound)
{
var valuesForActivity = new Bundle();
if (!string.IsNullOrEmpty(ClickAction)) valuesForActivity.PutString("ClickAction", ClickAction);
var intent = new Intent(this, Notification.Act.GetType());

intent.AddFlags(ActivityFlags.ClearTop);
intent.PutExtras(valuesForActivity);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

var notificationBuilder = new NotificationCompat.Builder(this)
.SetSmallIcon(ApplicationInfo.Icon)
.SetContentTitle(Title)
.SetContentText(Body)
.SetContentIntent(pendingIntent)
.SetSound(string.IsNullOrEmpty(Sound) ? null : RingtoneManager.GetDefaultUri(RingtoneType.Notification))
.SetChannelId(AdnroidNotification.CHANNEL_ID)
.SetStyle(new NotificationCompat.BigTextStyle().BigText(Body))
.SetAutoCancel(true);

var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(0, notificationBuilder.Build());
}

}

Implementation of Push Notification on Xamarin iOS:


1- Go to https://console.firebase.google.com and click on the same project you created on Android section.
2- add GoogleService-Info.plist to your iOS project root
3- right click on GoogleService-Info.plist on Visual studio, and in properties, set the buildaction => bundleresource
4- Install nuget package => Xamarin.Firebase.iOS.CloudMessaging
5- Install nuget package => xamarin.googleplayservices.base
6- remove all green-icon android support nuget pacakages (if exist)
7- update all other available nugets
8- Apple developer account -> in Certificates, IDs & Profiles -> Keys -> create APN key -> upload it in firebase console.
9- Apple developer account -> Certificates -> add certificate for notification for this specific app project.
10- In you Xamarin.iOS project your AppDelegate.cs file will look like this:

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
var del = new AppDelegate_Notification();
Firebase.Core.App.Configure();
// Register your app for remote notifications.
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.Current.Delegate = del;

var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) => {
Console.WriteLine(granted);
});
}
else
{
// iOS 9 or before
var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
}

UIApplication.SharedApplication.RegisterForRemoteNotifications();
Messaging.SharedInstance.Delegate = del;
//Messaging.SharedInstance.ShouldEstablishDirectChannel = true;



global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
var result = base.FinishedLaunching(app, options);
return result;
}

11- Create a class in you Xamarin.iOS project and add this code:

public class AppDelegate_Notification : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate, UserNotifications.IUNUserNotificationCenterDelegate, Firebase.CloudMessaging.IMessagingDelegate
{
// Receive displayed notifications for iOS 10 devices.
// Handle incoming notification messages while app is in the foreground.
[Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")]
public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
{
var userInfo = notification.Request.Content.UserInfo;

// With swizzling disabled you must let Messaging know about the message, for Analytics
//Messaging.SharedInstance.AppDidReceiveMessage (userInfo);

// Change this to your preferred presentation option
completionHandler(UNNotificationPresentationOptions.Alert);
}

// Handle notification messages after display notification is tapped by the user.
[Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
{
var userInfo = response.Notification.Request.Content.UserInfo;
var Aps = (NSDictionary)userInfo["aps"];
var Alert = (NSDictionary)Aps["alert"];
var Title = (NSString)Alert["title"];
var Body = (NSString)Alert["body"];
var ClickAction = (NSString)Aps["category"];
var Sound = (NSString)Aps["sound"];
{
DN.Modules.IOpener service = DependencyService.Get<DN.Modules.IOpener>(DependencyFetchTarget.NewInstance);
using (service as IDisposable)
{
service.Open(ClickAction);
}
}
completionHandler();
}

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
Messaging.SharedInstance.ApnsToken = deviceToken;
}

[Export("messaging:didReceiveRegistrationToken:")]
public void DidReceiveRegistrationToken(Messaging messaging, string fcmToken)
{
DN.Modules.Notification.CheckRegisteringDevice(fcmToken);
}

public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{

completionHandler(UIBackgroundFetchResult.NewData);
}

[Export("messaging:didReceiveMessage:")]
public void DidReceiveMessage(Messaging messaging, RemoteMessage remoteMessage)
{
}

public class UserInfoEventArgs : EventArgs
{
public NSDictionary UserInfo { get; private set; }
public MessageType MessageType { get; private set; }

public UserInfoEventArgs(NSDictionary userInfo, MessageType messageType)
{
UserInfo = userInfo;
MessageType = messageType;
}
}

public enum MessageType
{
Notification,
Data
}
}

What are push notifications?

Note:

IOS emulator cannot support remote notifications, it is better to use a physical device to support them.
Without the need for previous experience or technical knowledge, by mentioned and following steps of this training and observing its principles, you can get acquainted with and benefit from the following aspects.
• Xamarin and
Xamarin forms
• Google Firebase console
• Microsoft Azure and how to send push notifications through Azure Notification Hubs.
• Apple Developer Portal
• ASP.NET Core and Web API

How to set up Push Notification and Azure Notification Hub services (For UWP platform)

Azure notification hub hub is usually used to send notifications to a Xamarin Android application. These notifications are broadcasted over all the android devices using the Firebase Cloud Messaging feature.

To send push notifications to follow the below-given steps:

1- You have to create a Firebase project and have to enable the
Firebase Firebase Cloud Messaging feature.
2- Now create a notification hub.
3- Introduce the Xamarin. Android app and develop a connection with the notification hub.
4- Now send test notifications from the Azure portal.
ENABLING FIREBASE CLOUD NOTIFICATION:
1- Sign in to Firebase console and create a new project.
2- Add Firebase to your android application

3- Declare a name for the application, register your app, download googleservices.json.
4- Select project settings, make a selection on the Cloud Messaging option on the top, and save the generated server key.

DEVELOPING A MICROSOFT NOTIFICATION HUB:


1. Enter the Azure portal
2. Select the notification center in the mobile section.
3. In the generated page, select Add, enter a name, select a value for the location and a group of available resources.
4. Select the provided access policies.

Establish a connection between XAMARIN ANDROID APP and Hub Alert:


1. Create a VS project.
2. Select the available File option, then click on the project.
3. In your project, expand Visual C #, click on Android and select Android App (Xamarin).
4. Now after that, announce a name for the project and select the location, and finally select ok to continue your work.

You will be notified that you must have an Azure account, a Visual Studio with Xamarin on Windows, or a Visual Studio for Mac on OS X and an active Google Account.

Some of the main features of Xamarin are:


• Use of a single language: Xamarin • only uses C# as a native tool for the development of mobile-based applications. Unlike other interpreters, it is a go-to precision for building high-performance applications.
• The .NET framework comes across many features like LINQ, Asynchronous programming, Lambdas, and, based on C#, can be used as a tool for better programming aspects.
• Xamarin supports access to the latest APIs to acquire its capabilities in applications such as in ARKit on IOS or Android Multi-Window.

Source: https://www.dotnek.com/Blog/Apps/enabling-xamarin-push-notifications-for-all-p

Youtube: https://youtu.be/PVzbQnFrHmU